from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List

from database.database import get_db
from core.base.api_mode import ApiResponse, api_success
from ..schemas.gen_business_schema import GenBusinessCreate, GenBusinessUpdate, GenBusinessQuery
from ..vos.gen_business_vo import GenBusinessResponse
from ..services.gen_business_service import GenBusinessService


router = APIRouter()


@router.post("/create", response_model=ApiResponse[GenBusinessResponse])
async def create_gen_business(gen_business_data: GenBusinessCreate, db: AsyncSession = Depends(get_db)):
    """创建新的代码生成业务"""
    gen_business = await GenBusinessService.create_gen_business(db, gen_business_data)
    return api_success(
        GenBusinessResponse.model_validate(gen_business), msg="创建成功"
    )


@router.post("/list", response_model=ApiResponse[List[GenBusinessResponse]])
async def get_all_gen_businesses(query: GenBusinessQuery, db: AsyncSession = Depends(get_db)):
    """获取所有代码生成业务"""
    
    gen_businesses = await GenBusinessService.get_all_gen_businesses(db, query)
    return api_success(
        [GenBusinessResponse.model_validate(g) for g in gen_businesses], msg="获取成功"
    )


@router.get("/detail/{gen_business_id}", response_model=ApiResponse[GenBusinessResponse])
async def get_gen_business(gen_business_id: int, db: AsyncSession = Depends(get_db)):
    """获取单个代码生成业务详情"""
    gen_business = await GenBusinessService.get_gen_business_by_id(db, gen_business_id)
    if not gen_business:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="代码生成业务不存在"
        )
    return api_success(
        GenBusinessResponse.model_validate(gen_business), msg="获取成功"
    )


@router.put("/update/{gen_business_id}", response_model=ApiResponse[GenBusinessResponse])
async def update_gen_business(
    gen_business_id: int,
    gen_business_data: GenBusinessUpdate,
    db: AsyncSession = Depends(get_db),
):
    """更新代码生成业务"""
    gen_business = await GenBusinessService.update_gen_business(
        db, gen_business_id, gen_business_data
    )
    if not gen_business:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="代码生成业务不存在"
        )
    return api_success(
        GenBusinessResponse.model_validate(gen_business), msg="更新成功"
    )


@router.delete("/delete/{gen_business_id}", response_model=ApiResponse[dict])
async def delete_gen_business(
    gen_business_id: int, db: AsyncSession = Depends(get_db)
):
    """删除代码生成业务"""
    success = await GenBusinessService.delete_gen_business(db, gen_business_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="代码生成业务不存在"
        )
    return api_success({}, msg="删除成功")